clear all
global system "linux"

if "${system}" == "linux" {
	global code "/"
	global s "/"
}

run "${code}${s}_set-path.do"


use "${temp}/embs-prep.dta", clear
gen year = year(dofm(orig_ym))
keep if year <= 2013

joinby state_id orig_ym agency_id orig_rate orig_loan_amount orig_loan_to_value using "${temp}/lps-prep.dta", unmatched(master)
keep if _merge==3
drop _merge


// distance in debt_to_income
gen diff_debt_to_income = abs(debt_to_income - debt_to_income_ratio)
keep if diff_debt_to_income == 0

gen diff_fico = abs(fico- credit_score)


// break remaining ties using fico distance
sort embs_id diff_fico diff_debt_to_income appraisal_amount min_date mcdash_id
by embs_id: keep if _n==1
drop fico  

keep if orig_loan_to_value <= 80

save "${temp}/embs-lps-matched.dta", replace
